
// import 'dart:io';

import 'dart:io';

import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';
import 'dart:async';

import 'package:flutter_hotwork/Myapplication.dart';
import 'package:logger/logger.dart';
import 'package:shared_preferences/shared_preferences.dart';

/*
 * 封装 restful 请求
 *
 * GET、POST、DELETE、PATCH
 * 主要作用为统一处理相关事务：
 *  - 统一处理请求前缀；
 *  - 统一打印请求信息；
 *  - 统一打印响应信息；
 *  - 统一打印报错信息；
 */
class DioUtils {
  /// global dio object
  static Dio dio;

  /// default options
  /// //盐城
  // static const String API_PREFIX = 'http://222.188.27.206:8088/yc_rw';

  //连云港

  // static const String API_PREFIX = 'http://218.92.38.66:50002/yc_rw';

  //淮北
  // static  String API_PREFIX = 'http://112.122.189.119:8088/yc_rw';
//宣城
//   static  String API_PREFIX = 'http://117.70.117.78:8088/yc_rw';
  //福建
  // static  String API_PREFIX = 'http://59.61.236.243:8088/yc_rw';
  // static String API_PREFIX = 'http://146.56.248.16:8007/yc_rw';//云服务器
  // static String API_PREFIX = 'http://10.0.0.16:8088/yc_rw';//测试
  static String API_PREFIX = 'http://175.27.130.214:8081/xc_rw';//测试

  static const int CONNECT_TIMEOUT = 100000;
  static const int RECEIVE_TIMEOUT = 30000;

  /// http request methods
  static const String GET = 'get';
  static const String POST = 'post';
  static const String PUT = 'put';
  static const String PATCH = 'patch';
  static const String DELETE = 'delete';
  static String token = "";

  ///Get请求测试
  static void getHttp() async {
    try {
      Response response = await Dio().get("http://www.google.cn");
      print("response$response");
    } catch (e) {
      print(e);
    }
  }

  ///Post请求测试
  static void postHttp<T>(
      String url, {
        parameters,
        Function(T t) onSuccess,
        Function(String error) onError,
      }) async {

    ///定义请求参数
    parameters = parameters ?? {};
    //参数处理
    parameters.forEach((key, value) {
      if (url.indexOf(key) != -1) {
        url = url.replaceAll(':$key', value.toString());
      }
    });

    try {
      Response response;
      Dio dio = createInstance();
      response = await dio.post(url, data: parameters);
      if (response.statusCode == 200) {
        if (onSuccess != null) {
          onSuccess(response.data);
        }
      } else {
        throw Exception('statusCode:${response.statusCode}');
      }
      print('响应数据：' + response.toString());
    } catch (e) {
      print('请求出错：' + e.toString());
      onError(e.toString());
    }
  }

  // /**
  //  * 上传文件
  //  * 注：file是服务端接受的字段字段，如果接受字段不是这个需要修改
  //  */
  // Future<Response> uploadFile(String filePath, String fileName) async {
  //   var postData = FormData.fromMap(
  //       {"file": await MultipartFile.fromFile(filePath, filename: fileName)});//file是服务端接受的字段字段，如果接受字段不是这个需要修改
  //   var option = Options(method: "POST", contentType: "multipart/form-data");//上传文件的content-type 表单
  //   return await dio.post(
  //     data: postData,
  //     options: option,
  //     onSendProgress: (int sent, int total) {
  //     },
  //   );
  // }
  /// request method
  //url 请求链接
  //parameters 请求参数
  //metthod 请求方式
  //onSuccess 成功回调
  //onError 失败回调yc_rw/files
  static Future<Map> request<T>(String url,
      {parameters,
        method,
        Function(T t) onSuccess,
        Function(String error) onError}) async {
    parameters = parameters ?? {};
    method = method ?? 'GET';

    /// 请求处理
    parameters.forEach((key, value) {
      if (url.indexOf(key) != -1) {
        url = url.replaceAll(':$key', value.toString());
      }
    });

    /// 打印:请求地址-请求方式-请求参数
    print('请求地址：【' + method + '  ' + url + '】');
    print('请求参数：' + parameters.toString());

    Dio dio = createInstance();
    //请求结果
    var result;
    try {
      Response response = await dio.request(url,
          data: parameters, options: new Options(method: method));
      result = response.data;
      if (response.statusCode == 200) {
        if (onSuccess != null) {
          onSuccess(result);
        }
      } else {
        throw Exception('statusCode:${response.statusCode}');
      }
      print('响应数据：' + response.toString());
    } on DioError catch (e) {
      print('请求出错：' + e.toString());
      onError(e.toString());
    }

    return result;
  }

  /// 创建 dio 实例对象
  static Dio createInstance() {
    if (dio == null) {
    /// 全局属性：请求前缀、连接超时时间、响应超时时间
    var options = BaseOptions(
      connectTimeout: 150000,
      receiveTimeout: 150000,

      responseType: ResponseType.plain,
      validateStatus: (status) {
        // 不使用http状态码判断状态，使用AdapterInterceptor来处理（适用于标准REST风格）
        return true;
      },
      baseUrl: API_PREFIX,
    );
    dio = new Dio(options);
    print('token--'+token);
    Logger().d("token=======$token");
    dio.options.headers = {"X-Access-Token":"$token"};
    getIPAddress();



//     (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
//         (client) {
//       // config the http client
//       client.findProxy = (uri) {
//         return "PROXY 10.0.0.16:8888";//如果设置代理（localhost,127.0.0.1这样的是不行的。必须是电脑的ip）
// //        return 'DIRECT';// 如果不设置代理
//       };
//       client.badCertificateCallback =
//           (X509Certificate cert, String host, int port) => true;//忽略证书
//     };




    }
    return dio;
  }
  static getIPAddress() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    if(prefs.containsKey("ip")&&prefs.getString("ip").length>10){
      API_PREFIX = prefs.getString("ip");
    }

  }
  /// 清空 dio 对象
  static clear() {
    dio = null;
  }

}